﻿using System;
using System.Text;
using TdxHq.Invoker;

namespace TdxHq.Connect
{
    public class TdxConnection
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("TdxConnection");
        
        public string Ip { get; }
        public int Port { get; }
        public DllInvoker Invoker { get; }
        public bool Connected { get; set; }
        public long Delay { get; set; }
        private volatile bool _usering  = false;
        public string ConnectionName { get; set; }

        public int ConnectTime = 0;
        
        private readonly object _lock = new object();
        
        public bool IsUsing()
        {
            bool b = false;
            lock (_lock)
            {
                b = _usering;
            }
            return b;
        }

        public bool Connect()
        {
            ConnectTime++;
            StringBuilder result = new StringBuilder(1024 * 1024);
            StringBuilder errInfo = new StringBuilder(256);
            QuoteDelegate.TdxHq_Connect connectDelegate = (QuoteDelegate.TdxHq_Connect)Invoker.Invoke("TdxHq_Connect", typeof(QuoteDelegate.TdxHq_Connect));
            Connected = connectDelegate(Ip, Port, result, errInfo);

            Log.Info("------------------------------");
            Log.Info("重连服务器:" + result);
            Log.Info("IP:" + Ip);

            if (!Connected)
            {
                Log.Error("errInfo:" + errInfo);
                Log.Error("重连失败");
            }
            
            Log.Error("------------------------------");
            
            return Connected;
        }

        public bool GetSecurityQuotes(byte[] market, string[] zqdm, ref short count, StringBuilder result, StringBuilder errInfo)
        {
            lock (_lock)
            {
                _usering = true;
            }

            QuoteDelegate.TdxHq_GetSecurityQuotes getSecurityQuotes =
                (QuoteDelegate.TdxHq_GetSecurityQuotes) Invoker.Invoke("TdxHq_GetSecurityQuotes",
                    typeof(QuoteDelegate.TdxHq_GetSecurityQuotes));
            
            lock (_lock)
            {
                _usering = false;
            }

            var ticks1 = DateTime.Now.Ticks;
            bool success = getSecurityQuotes(market, zqdm, ref count, result, errInfo);
            var ticks2 = DateTime.Now.Ticks;
            Delay = ticks2 - ticks1;
            
//            Console.WriteLine("服务器:"+ConnectionName +"\tIP:"+Ip+"\t延迟:"+Delay/10000+"ms");

            if(!success)
            {
                Connected = false;
                var connected = Connect();
                if (connected)
                {
                    ConnectTime = 0;
                }
            }
            
            return success;
        }

        public TdxConnection(string ip, int port, DllInvoker invoker)
        {
            Ip = ip;
            Port = port;
            Invoker = invoker;
        }
    }
}